﻿namespace HyperLinq.Abstract
{
	using System.Collections.Generic;

	internal class MultidimensionalArrayEnumerator<T> : IEnumerator<T>
	{
		public MultidimensionalArrayEnumerator(MultidimensionalArrayEnumerable<T> source)
		{
			enumerable = source;

			this.Reset();
		}

		private MultidimensionalArrayEnumerable<T> enumerable;

		private int[] cursor;

		public T Current
		{
			get { return (T)enumerable.Array.GetValue(cursor); }
		}

		public bool MoveNext()
		{
			cursor[enumerable.Array.Rank - 1]++;

			for (int i = enumerable.Array.Rank - 1; i > 0; i--)
			{
				if (cursor[i] >= enumerable.Array.GetLength(i))
				{
					cursor[i - 1]++;
					cursor[i] = 0;
				}
			}

			return cursor[0] < enumerable.Array.GetLength(0);
		}

		public void Reset()
		{
			cursor = new int[enumerable.Array.Rank];
			cursor[enumerable.Array.Rank - 1] = -1;
		}

		object System.Collections.IEnumerator.Current
		{
			get { return this.Current; }
		}

		public void Dispose()
		{
		}
	}
}
